##evented-async-loop
Loop through asynchronous code with events
Installation
npm install evented-async-loop
Usage
Check examples
and test
folders for more details.
Basic
'use strict';
var asyncLoop = require('../index');
var dummyArray = require('./dummyArray');
var arr = dummyArray(10);
var loop = asyncLoop.create(arr);
loop.on('next', function (elm, i, array) {
elm(function() {
console.log(i);
loop.next();
});
});
loop.on('done', function () {
console.log('Done!');
});
loop.start();
Chaining
loop.on('next', function (elm, i, array) {
elm(function () {
console.log(i);
loop.next();
});
}).on('done', function () {
console.log('Done!');
}).start();
Exit early
loop.on('next', function (elm, i, array) {
elm(function () {
if (i === 5) {
loop.done(i, 'i am Batman');
}
loop.next();
});
}).on('done', function (i, msg) {
console.log('Loop stopped at %s and %s', i, msg);
}).start();
Data propagation
loop.on('next', function (elm, i, array, arg1, arg2) {
elm(function () {
loop.next(++arg1, arg2);
});
}).on('done', function (arg1, arg2) {
console.log('arg1: %s, arg2: %s', arg1, arg2);
}).start(0, 'blah');
Error handling
loop.on('next', function (elm, i, array) {
elm(function () {
if (i === 3) {
loop.error('Oh noez!');
}
if (i === 8) {
loop.break().error('This will stop the loop');
}
loop.next();
});
}).on('done', function () {
console.log('Done!');
}).on('error', function (err) {
console.log(err);
}).start();
##API
###Events
next[element, i, array, arg1, ...]
done[arg1, ...]
error[arg1, ...]
###Methods
.start([arg1, ...])
: Start the loop.Passes arguments to the first next
event.next([arg1, ...])
: Go to the next iteration. Passes agruments to next
event. If the loop is completed done
is emitted instead..done([arg1, ...])
: Stop the loop early. Passes arguments to done
event.error([err])
: Emit an error
event.break()
: Break the loop. it wont emit done
##Test
Change your working directory to the project's root, npm install
to get the development dependencies and then npm test